<template>
  <div id="list-container" ref="listContainer">
    <ul id="list" ref="ulElement">
      <div id="lis" @mouseover="handleMouseOver" @mouseout="handleMouseOut" ref="lis">
        <!-- 内容插槽 -->
        <slot name="content" />
      </div>
    </ul>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        isHovered: false,
        scrollTimeout: null,
        frist: 0,
        listContainerHeight: 0,
        lisHeight: 0,
        liElements: null,
        clonedLiElements: []
      }
    },
    mounted() {
      setTimeout(() => {
        this.listContainerHeight = this.$refs.listContainer.offsetHeight
        this.lisHeight = this.$refs.lis.offsetHeight
        this.liElements = this.$refs.lis.childNodes // 获取所有子节点
        this.startAutoScroll()
      }, 5500)
    },
    methods: {
      handleMouseOver() {
        this.isHovered = true
        clearTimeout(this.scrollTimeout)
      },
      handleMouseOut() {
        this.isHovered = false
        this.startAutoScroll()
      },
      startAutoScroll() {
        clearTimeout(this.scrollTimeout)
        if (!this.isHovered) {
          this.scrollTimeout = setTimeout(this.autoScroll, 40)
        }
      },
      autoScroll() {
        if (!this.isHovered) {
          this.$refs.listContainer.scrollTop += 1
          // console.log(this.$refs.listContainer.scrollTop);
          if (this.$refs.listContainer.scrollTop >= this.lisHeight && this.frist !== 0) {
            this.$refs.listContainer.scrollTop = 0
          }
          if (this.$refs.listContainer.scrollTop === this.lisHeight - this.listContainerHeight) {
            if (this.frist === 0) {
              this.frist += 1
              // 复制每个 <li> 元素并添加到 <ul>
              for (var i = 0; i < this.liElements.length; i++) {
                var originalLi = this.liElements[i]
                var clonedLi = originalLi.cloneNode(true)
                this.clonedLiElements.push(clonedLi)
              }
              // 将数组中的每个复制的 <li> 元素添加到目标 <ul> 元素中
              for (var i = 0; i < this.clonedLiElements.length; i++) {
                this.$refs.lis.appendChild(this.clonedLiElements[i])
              }
            }
          }
        }
        this.scrollTimeout = setTimeout(this.autoScroll, 40)
      },
    },
    beforeDestroy() {
      clearTimeout(this.scrollTimeout)
    },
  }
</script>
<style lang="scss" scoped>
  #list-container {
    height: 100%; /* 设置容器的高度 */
    overflow-y: auto; /* 设置容器为垂直滚动 */
  }

  #list {
    list-style-type: none; /* 去除列表的默认样式 */
    padding: 0;
    margin: 0;
    white-space: nowrap; /* 使列表项水平排列 */
  }
  /* 滚动条样式 */
  #list-container::-webkit-scrollbar {
    display: none;
  }
</style>
